<!-- 新增检测任务单(委托型) -->
<template>
  <div class="dialog-container" id="dialog-container">
    <el-dialog v-dialogDrag :fullscreen="isFullScreen" :custom-class="isFullScreen?'fullscreen-default-dialog':'vertical-center-dialog'" append-to-body :close-on-click-modal="false" :visible.sync="dialogVisible" @close="$emit('update:show', false)" :before-close="handleClose"
      :show="show" width="800px">
      <div slot="title">
        <span style="color:white;">新增</span>
        <button type="button" aria-label="fullScreen" class="el-dialog__headerbtn" style="margin-right:25px;" @click="isFullScreen = !isFullScreen">
                                          <i class="el-dialog__close iconfont icon-fuzhicopy22"></i>
                                      </button>
      </div>
      <div style="overflow: hidden;">
        <img src="../../../../assets/images/sagw.png" style="float:left;">
        <h2 style="text-align:center;">新增检测任务单（委托型）</h2>
      </div>
      <el-form :model="form" :rules="rules" ref="form" :inline="true" label-width="130px" size="small">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="1.基础信息" name="first">
            <el-row>
              <el-col :span="12">
                <el-form-item label="委托单号：" prop="taskNo">
                  <!-- <el-input v-model="form.taskNo" disabled></el-input> -->
                  {{form.taskNo}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="委托日期：" prop="applyTime">
                  <!-- <el-date-picker v-model="form.applyTime" type="date" style="width: 200px;"></el-date-picker> -->
                  {{ form.currentTime }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="任务类型：" prop="taskType">
                   <!--  <el-input v-model="form.taskType" disabled auto-complete="off"></el-input> -->
                  {{ form.taskType1 }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="委托部门：" prop="applyOrgName">
                  <!-- <el-input v-model="form.applyOrgName" auto-complete="false"></el-input> -->
                  {{form.applyUser?form.applyUser.org.name:''}}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="委托人：" prop="applyUser">
                  <!-- <el-input v-model="form.applyUser" auto-complete="false"></el-input> -->
                  {{form.applyUser?form.applyUser.name:''}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="需求完成日期：" prop="expectCompleteTime">
                  <el-date-picker v-model="form.expectCompleteTime" value-format="yyyy-MM-dd"  type="date" style="width: 200px;"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                实验室将尽力配合,但不承诺在需求完成日期内完成。
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="2.零件信息" name="second">
            <el-row>
              <el-col :span="12">
                <el-form-item label="项目号：" prop="projectNo">
                <!--<el-input v-model="form.projectNo" auto-complete="false" :disabled="canNotEdit"></el-input>-->
                     <el-input v-model="form.projectNo" auto-complete="false" disabled></el-input>

                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="零件号：" prop="partNumber">
                  <el-autocomplete v-model="form.partNumber" style="width: 200px;float: left;" :fetch-suggestions="querySearchAsync" placeholder="请输入内容" @select="handleSelect" @change="changeField" ></el-autocomplete>
                  <!-- <el-input v-model="form.partNumber" style="width: 100px;float: left;" @change="changeField"></el-input> -->
                  <select-part-number-button @partVal="getPartVal" :partNumber="form.partNumber" style="display: inline-block;margin-left: 8px;"></select-part-number-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="零件图号：" prop="partGraphNumber">
                 <!-- <el-input v-model="form.partGraphNumber" :disabled="canNotEdit"></el-input>-->
                  <el-input v-model="form.partGraphNumber" auto-complete="false" disabled></el-input>

                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="零件名称：" prop="partName">
                 <!-- <el-input v-model="form.partName" :disabled="canNotEdit"></el-input>-->
                   <el-input v-model="form.partName" auto-complete="false" disabled></el-input>
 
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="材料牌号：" prop="materialNo">
                  <!--<el-input v-model="form.materialNo" auto-complete="false" :disabled="canNotEdit"></el-input>-->
                    <el-input v-model="form.materialNo" auto-complete="false" disabled></el-input>
       </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="批次零件总数量：" prop="totalPartNo">
                  <el-input-number :controls='false' style='text-align:left' :precision='0' v-model="form.totalPartNo"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="样品状态阶段：" prop="sampleStatusPhase">
                  <el-select v-model="form.sampleStatusPhase" filterable placeholder="请选择" style="width: 200px;">
                    <el-option v-for="item in sampleStatusPhaseList" :key="item.code" :label="item.name" :value="item.code">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="原材料炉号：" prop="materialFurnanceNumber">
                  <el-input v-model="form.materialFurnanceNumber"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="3.样品信息" name="third">
            <el-row>
              <el-col :span="12">
                <el-form-item label="热处理炉号：" prop="heatingNumber">
                  <el-input v-model="form.heatingNumber" auto-complete="false"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <!-- <el-form-item label="样品状态：" prop="sampleStatus">
                  <el-input v-model="form.sampleStatus" auto-complete="off"></el-input>
                </el-form-item> -->
                <el-form-item label="样品状态：" prop="sampleStatus"> 
                    <el-select v-model="form.sampleStatus" filterable placeholder="请选择" style="width: 200px;" >
                      <el-option v-for="item in sampleStatusDropList" :key="item.code" :label="item.name" :value="item.code">
                      </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="样品数量：" prop="quantity">
                  <el-input-number :controls='false' style='text-align:left' :precision='0' v-model="form.quantity"></el-input-number>
                </el-form-item>
              </el-col>
               <el-col :span="12">
                <el-form-item label="供应厂商：" prop="provider">
                  <el-input v-model="form.provider"></el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                              <el-form-item label="批次信息：" prop="batchNumber">
                                <el-input v-model="form.batchNumber" auto-complete="false"></el-input>
                              </el-form-item>
                            </el-col> -->
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="备注：" prop="remark">
                  <el-input type="textarea" v-model="form.remark" auto-complete="false" style="width: 580px;"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
        <el-card shadow="never">
          <div slot="header" class="clearfix">
            <span>任务内容、目的与需求：</span>
          </div>
          <el-row>
            <el-col :span="22" :offset="2">
              <el-form-item label="" prop="taskTarget">
                <el-radio-group v-model="form.taskTarget">
                  <el-radio label="新产品试制">新产品试制</el-radio>
                  <el-radio label="常规均匀性实验">常规均匀性实验</el-radio>
                  <el-radio label="失效零件分析">失效零件分析</el-radio>
                  <el-radio label="复检">复检</el-radio>
                  <el-radio label="设备新增/大修验收">设备新增/大修验收</el-radio>
                  <el-radio label="其他">其他</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
      <br>
      <!-- <selection-of-experimental-items-button @testPros="getTestPros"></selection-of-experimental-items-button> -->

      <!-- 表格 -->
      <br>
      <el-tabs v-model="activeSampleInspectionContentsName" @tab-click="handleClick">
        <el-tab-pane :label="item.title" :name="item.title" v-for="item in editableTabs" :key="item.id">
          <sample-inspection-contents :tableData='testProData'></sample-inspection-contents>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit('form')">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import SampleInspectionContents from 'module/sample-inspection-contents';
  import SelectPartNumber from '../select-part-number-button'; // 选择零件号
  import TestPro from '../selection-of-experimental-items-button'; // 新增检测项目

  import {
    changeFormitemSpace
  } from '../../../../utils/common' // 表单验证有误时，改变表单的上下间距
  import {
    postSaveApplyService,
    getPartList,
    getUserInfo,
    getFiledListByPartId,
    getStandardCondition,
    getSampleStatusPhase,
    getApplyInfoByIdService,
    getNextTaskNo,
    postSubmitApplyService,
    getPartNumberList,
    getSampleStatusDrop
  } from 'service/task';

  import {
    APPLY_TYPE_LIST,
    APPLY_STATUS_LIST
  } from '../../../../service/constant'

  import {
    getLableFromList,
    dateFormat
  } from '../../../../utils/common'

  export default {
    components: {
      'select-part-number-button': SelectPartNumber,
      //'selection-of-experimental-items-button': TestPro,
      'sample-inspection-contents': SampleInspectionContents,
    },
    data() {
      return {
        sampleStatusPhaseList: [],
        sampleStatusDropList:[],
        sampleTabNumber: 1,

        editableTabs: [{
          'id': 1,
          'title': '样品1'
        }],
        isFullScreen: true,
        dialogVisible: this.show,
        activeName: 'first',
        activeSampleInspectionContentsName: '样品1',
        operatorList: [],
        partNumberList: [],
        partNumber: String,
        canNotEdit: true,
        form: {
          currentTime: dateFormat(new Date()),
          taskNo: '',
          applyTime: new Date(),
          taskType: '1',
           taskType1: '委托型',
          // applyOrgName: '',
          // applyUser: localStorage.getItem("username"),
          applyUser: JSON.parse(localStorage.getItem('currentUser')),
          expectCompleteTime: '',
          projectNo: '',
          partNumber: '',
          partGraphNumber: '',
          partName: '',
          materialNo: '',
          totalPartNo: null,
          sampleStatusPhase: '',
          materialFurnanceNumber: '',
          heatingNumber: '',
          sampleStatus: '',
          quantity: 1,
          batchNumber: '',
          provider: '',
          remark: '',
          taskTarget: ''
        },
        rules: {
          expectCompleteTime: [{
            required: true,
            message: '请选择需求完成日期',
            trigger: 'blur'
          }],
          sampleStatusPhase: [{
            required: true,
            message: '请选择样品状态阶段',
            trigger: 'blur'
          }],
          heatingNumber: [{
            required: true,
            message: '请输入热处理炉号',
            trigger: 'blur'
          }],

          partNumber: [{
            required: true,
            message: '请输入或选择零件号',
            trigger: 'blur'
          }],
          partGraphNumber: [{
            required: true,
            message: '请输入零件图号',
            trigger: 'blur'
          }],
          quantity: [{
            required: true,
            message: '请输入样品数量',
            trigger: 'blur'
          }],
          taskTarget: [{
            required: true,
            message: '请输入任务内容、目的与需求',
            trigger: 'blur'
          }],
          sampleStatus: [{
            required: true,
            message: '请输入样品状态',
            trigger: 'blur'
          }]
        },
        testFields: '', // 新增检测项目值
        testProData: [] // 新增检测项目的值
      }
    },
    props: {
      show: {
        type: Boolean,
        default: false,
      },
      copyId: {
        type: String
      }
    },
    watch: {

      show() {
        getSampleStatusPhase().then(res => {
          for(let i=0; i<res.data.result.length; i++){
            if(res.data.result[i].display=="是"){
              this.form.sampleStatusPhase=res.data.result[i].code;
            }
          }
        });
        this.dialogVisible = this.show;
        this.activeName = 'first';
        if (this.dialogVisible) {

          if (this.copyId && this.copyId != '') {
            getApplyInfoByIdService(this.copyId).then(res => {
              // console.log(res.data.result.taskTarget);
              // this.form.taskNo = ;
              // this.form.applyTime = res.data.result.applyTime;
              // this.form.taskType = res.data.result.taskType;
              // this.form.applyOrgName = res.data.result.applyUser.org.name;
              // this.form.applyUser = res.data.result.applyUser.name;
              // this.form.expectCompleteTime = res.data.result.expectCompleteTime;
              // this.form.projectNo = res.data.result.projectNo;
              // this.form.partNumber = res.data.result.partNumber;
              // this.form.partGraphNumber = res.data.result.partGraphNumber;
              // this.form.partName = res.data.result.partName;
              // this.form.materialNo = res.data.result.materialNo;
              // this.form.totalPartNo = res.data.result.totalPartNo;
              // this.form.sampleStatusPhase = res.data.result.sampleStatusPhase;
              // this.form.materialFurnanceNumber = res.data.result.materialFurnanceNumber;
              // this.form.heatingNumber = res.data.result.heatingNumber;
              // this.form.sampleStatus = res.data.result.sampleStatus;
              // this.form.quantity = res.data.result.quantity;
              // this.form.batchNumber = res.data.result.batchNumber;
              // this.form.provider = res.data.result.provider;
              // this.form.remark = res.data.result.remart;
              // this.form.taskTarget = taskTarget;
              this.form = res.data.result;
              // this.form.taskTarget = this.form.taskTarget.split(",");
              this.form.id = null;
              this.form.taskNo = null;
              //this.form.expectCompleteTime = null;

              //this.quantity = this.form.quantity;

              this.form.applyTypeStr = getLableFromList(APPLY_TYPE_LIST, 1);
              this.form.currentTime = dateFormat(new Date());
              this.testProData = this.form.taskFieldList;
              for (let i = 0; i < this.testProData.length; i++) {
                // this.testProData[i].displayId = i + 1;
                this.testProData[i].operator = this.testProData[i].partField ? this.testProData[i].partField.operator : this.testProData[i].operator;
                this.testProData[i].operatorStr = getLableFromList(this.operatorList, this.testProData[i].partField ? this.testProData[i].partField.operator : this.testProData[i].operator);
                this.testProData[i].orginalCol1 = this.testProData[i].partField.col1;
                this.testProData[i].orginalCol2 = this.testProData[i].partField.col2;
                this.testProData[i].position = this.testProData[i].testPart;
                this.testProData[i].partField.fieldId = this.testProData[i].partField.id;
              }
              // getNextTaskNo().then(res => {
              //   this.form.taskNo = res.data.result;

              // });
              getUserInfo("/user/info")
                .then(res => {
                  // if (res.data.result.org) {
                  //   //this.form.applyOrgName = res.data.result.org.name;
                  // }
                  this.form.applyUser = res.data.result;
                })
            });

          } else {
            this.form = {
              currentTime: dateFormat(new Date()),
              taskNo: '',
              applyTime: new Date(),
               taskType: '1',
                taskType1: '委托型',
             // applyOrgName: '',
              // applyUser: localStorage.getItem("username"),
              applyUser: JSON.parse(localStorage.getItem('currentUser')),
              expectCompleteTime: '',
              projectNo: '',
              partNumber: '',
              partGraphNumber: '',
              partName: '',
              materialNo: '',
              totalPartNo: null,
              sampleStatusPhase: '',
              materialFurnanceNumber: '',
              heatingNumber: '',
              sampleStatus: '',
              quantity: 1,
              batchNumber: '',
              provider: '',
              remark: '',
              taskTarget: ''
            };
            let that = this;
            this.testProData = [];
            // getNextTaskNo().then(res => {
            //   that.form.taskNo = res.data.result;
            //   console.log(that.form);
            // });
            getUserInfo("/user/info")
              .then(res => {
                // if (res.data.result.org) {
                //   //this.form.applyOrgName = res.data.result.org.name;
                // }
                that.form.applyUser = res.data.result;
              })
          }


        }
      },
      quantity(newVal, oldVal) {
        if (newVal == undefined || newVal == "" || newVal == 0) {
          newVal = 1;
        }
        this.editableTabs.length = 0;
        for (let i = 1; i <= newVal; i++) {
          this.editableTabs.push({
            id: i,
            title: `样品${i}`,
          });
        }
      }
    },
    computed: {
      quantity() {
        return this.form.quantity;
      }
    },
    methods: {
      handleSelect(item) {
        this.form.projectNo = item['projectNo'];
        this.form.partGraphNumber = item['partGraphNumber'];
        this.form.partName = item['partName'];
        this.form.materialNo = item['materialNo'];
      },
      querySearchAsync(queryString, cb) {
                let partNumberList = this.partNumberList;
                let results = queryString ? partNumberList.filter(this.createStateFilter(queryString)) : partNumberList;
                if(!queryString) {
                  this.form.projectNo = '';
                  this.form.partGraphNumber = '';
                  this.form.partName = '';
                  this.form.materialNo = '';
                }
                if(results.length == 0) {
                  this.canNotEdit = false;
                } else {
                  this.canNotEdit = true;
                }
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 1000);
            },
            createStateFilter(queryString) {
                return (state) => {
                    return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },
      changeCol1(row) {
        if (Number(row.col1) < Number(row.orginalCol1)) {
          this.$alert('下限应该原区间范围内', '提示', {
            type: 'error'
          })
          return false;
        }
        if (row.orginalCol2) {
          if (Number(row.col1) > Number(row.orginalCol2)) {
            this.$alert('下限应该原区间范围内', '提示', {
              type: 'error'
            })
            return false;
          }
        }
        return true;
      },
      changeCol2(row) {
        if (row.col2 || row.orginalCol2) {
          if (Number(row.col2) < Number(row.orginalCol1) || Number(row.col2) > Number(row.orginalCol2)) {
            this.$alert('上限应该原区间范围内', '提示', {
              type: 'error'
            })
            return false;
          }
        }
        return true;
      },
      changeField() {
        if (this.form.partNumber) {
          this.testProData = [];
          getFiledListByPartId(this.form.partNumber).then(res => {
            // debugger;
            this.getTestPros(res.data.result);
          })
        }
      },
      handleClose() { /* 关闭的时候更新状态值 */
         let confirm = this.$confirm('是否需要关闭？', '提示', {
                  type: 'warning'
                }).then(confirmRes => {
                  this.isFullScreen = false;
                  this.dialogVisible = false;
                  this.$refs['form'].resetFields();
                 
                }).catch(cancelRes => {
                })
      },
      handleClick(tab, event) {
        // console.log(tab, event);
      },
      // 选择零件号的值
      getPartVal(val) {
        // console.log(val)
        this.form.partNumber = val.partNumber;
        this.form.partGraphNumber = val.partGraphNumber;
        this.form.partName = val.partName;
        this.form.materialNo = val.materialNo;
        this.form.projectNo = val.projectNo;
        this.form.part = val;
        this.changeField();
      },
      // 监听零件号输入框失去焦点事件
      partBulr() {
        getPartList({
          part_number: this.form.partNumber,
          part_graph_number: '',
          part_name: '',
          material_furnance_number: '',
          project_no: '',
          sample_status_phase: '',
          material_no: '',
          batch_number: ''
        }).then(res => {
          this.tableData = res.data.result.content;
          this.form.partNumber = res.data.result.content[0].part_number;
          this.form.partGraphNumber = res.data.result.content[0].part_graph_number;
          this.form.partName = res.data.result.content[0].part_name;
          this.form.materialNo = res.data.result.content[0].material_no;
        })
      },
      // 获取选择检测项目的值
      getTestPros(val) {
        // console.log(val)
        let names = [];
        for (let i = 0; i < val.length; i++) {
          names.push(val[i].id);
          // val[i].displayId = this.testProData.length + 1;
          val[i].testPart = val[i].position;
          val[i].standardName = val[i].standard;
          val[i].orginalCol1 = val[i].col1;
          val[i].orginalCol2 = val[i].col2;

          val[i].operatorStr = getLableFromList(this.operatorList, val[i].operator);
          this.testProData.push(val[i]);
        }
        this.testFields = names.join(',');
        //this.testProData = val;
      },
      reportWrong(){
          if(this.form.taskTarget == "") {
            alert("请输入任务内容、目的与需求");
            return;
          }
          if(this.form.expectCompleteTime == "") {
            alert("请输入需求完成日期");
            return;
          }
          if(this.form.partNumber == "") {
            alert("请输入零件号");
            return;
          }
          if(this.form.sampleStatusPhase == "") {
            alert("请输入样品状态阶段");
            return;
          }
          if(this.form.heatingNumber == "") {
            alert("请输入热处理炉号");
            return;
          }
          if(this.form.partGraphNumber == "") {
            alert("请输入零件图号");
            return;
          }
      },
      submit(formName) {
        this.$refs[formName].validate((valid) => {
          this.reportWrong();
          if (valid) {
            let names = [];
            for (let i = 0; i < this.testProData.length; i++) {

              if (!this.changeCol1(this.testProData[i]) || !this.changeCol2(this.testProData[i])) {
                return;
              }
              console.log(this.testProData[i]);
              names.push({
                id: this.testProData[i].partField ? this.testProData[i].partField.fieldId : this.testProData[i].id,
                col1: this.testProData[i].col1 + '',
                col2: this.testProData[i].col2 + ''
              });
              console.log(names);
            }

            console.log(this.testFields);
            postSaveApplyService({
              expectCompleteTime: this.form.expectCompleteTime,
              taskType: this.form.taskType,
              projectNo: this.form.projectNo,
              partNumber: this.form.partNumber,
              partGraphNumber: this.form.partGraphNumber,
              partName: this.form.partName,
              materialNo: this.form.materialNo,
              totalPartNo: this.form.totalPartNo,
              materialFurnanceNumber: this.form.materialFurnanceNumber,
              heatingNumber: this.form.heatingNumber,
              sampleStatus: this.form.sampleStatus,
              quantity: this.form.quantity,
              batchNumber: this.form.batchNumber,
              sampleStatusPhase: this.form.sampleStatusPhase,

              partId: this.form.part.id,
              part: this.form.part,
              provider: this.form.provider,
              remark: this.form.remark,
              taskTarget: this.form.taskTarget,
              testFields: names
            }).then(res => {
              if (res.data.success) {
                  this.$emit('refreshAdd');
                  this.dialogVisible = false;
              } else {
                this.$alert(res.data.message, '提示', {
                  type: 'error'
                })
              }

            })
          } else {
            changeFormitemSpace(document);
            return false;
          }
        });
      }
    },
    // mounted() {
    //   console
    // },

    mounted() {
      this.partNumberList = [];
      this.form.applyTypeStr = getLableFromList(APPLY_TYPE_LIST, 1);
      getStandardCondition().then(res => {
        this.operatorList = res.data.result;
      });
      getSampleStatusPhase().then(res => {
        this.sampleStatusPhaseList = res.data.result;
      });
      getSampleStatusDrop().then(res =>{
        this.sampleStatusDropList = res.data.result;
      })
      // getNextTaskNo().then(res => {
      //   this.form.taskNo = res.data.result;
      // })
      getPartNumberList().then(res => {
         if (res.status == '200') {
                    let list = res.data;
                    for (let i = 0; i < list.length; i++) {
                        let object = {};
                        object['value'] = list[i]['partNumber'];
                        object['projectNo'] = list[i]['projectNo'];
                        object['partGraphNumber'] = list[i]['partGraphNumber'];
                        object['partName'] = list[i]['partName'];
                        object['materialNo'] = list[i]['materialNo'];
                        this.partNumberList.push(object);
                    }
                }
      })
    }
  }
</script>
